package cn.est.controller;

import cn.est.constants.Constants;
import cn.est.dto.AppointmentReq;
import cn.est.dto.EvaluateDto;
import cn.est.dto.MalFunctionDto;
import cn.est.dto.Result;
import cn.est.pojo.Users;
import cn.est.service.EvaluateService;
import cn.est.service.MaintainOrderService;
import cn.est.service.MalfunctionService;
import cn.est.service.TokenService;
import cn.est.utils.DateUtils;
import cn.est.utils.RedisUtil;
import cn.est.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.List;

@Api
@RestController
@RequestMapping("api/evaluate")
public class EvaluateController {


     @Autowired
    private MalfunctionService malfunctionService;

     @Autowired
    private TokenService tokenService;

     @Autowired
     private EvaluateService evaluateService;


     @Autowired
     private RedisUtil redisUtil;

     @Autowired
     private MaintainOrderService maintainOrderService;


    @ApiOperation(value="旧商品维修维度",notes = "旧品维修评估维度")
    @ApiImplicitParam(name="modelId",required = true ,value = "商品类型id")
    @GetMapping("/specList")
    public Result<List<MalFunctionDto>>list(Integer modelId){
        List<MalFunctionDto>  malFunctionDtoList=  malfunctionService.getMalFunctionDto(modelId);
        return ResultUtils.returnDataSuccess(malFunctionDtoList);
    }


    /**
     * optionId：    1，7，11
     */
    @ApiOperation(value="維修估價",notes = "根據用戶前端選擇的故障信息，進行對價格的評估")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modelId",value = "商品型号Id"),
            @ApiImplicitParam(name = "optionIds",value = "商品故障选项ids"),
            @ApiImplicitParam(name = "token",value = "用户的token",paramType = "header")}
    )
    @PostMapping("/access")
    public Result<EvaluateDto> access(Integer modelId,String optionIds,HttpServletRequest request){

       // String token = request.getHeader("token");
       // Users user = tokenService.getLoginUser(token);
       // int userId=user.getId();
        int userId=1;
        EvaluateDto evaluateDto=   evaluateService.assess(modelId,optionIds,userId);
        return ResultUtils.returnDataSuccess(evaluateDto);
    }



        @ApiOperation(value ="維修估算詳情",notes = "根據id查询商品的估算详情信息")
        @ApiImplicitParam(name ="id",required = true,value = "评估id")
        @GetMapping("/{id}/accessInfo")
        public Result<EvaluateDto> acessInfo(@PathVariable Integer id){
            EvaluateDto data=evaluateService.getEById(id);
            if(data==null){
                return ResultUtils.returnFail("没有找到该评估记录");
            }else{
                return  ResultUtils.returnDataSuccess(data);
            }
        }



    @ApiOperation(value = "维修下单",notes = "维修下单")
    @ApiImplicitParams({
            @ApiImplicitParam(name ="evaluateId",required = true,value = "评估id"),
            @ApiImplicitParam(name ="appointmentReq",required = true,value = "订单信息"),
            @ApiImplicitParam( paramType = "header",name ="token",required = true,value = "token")
    })
    @PostMapping("/submit")
    public Result sumbmit(AppointmentReq appointmentReq, Integer evaluateId, HttpServletRequest request){
        //1.校验日期，不能早于今天，必须是4天内
            if(!checkAppDate(appointmentReq.getAppintDate())){
                return  ResultUtils.returnFail("预约日期有误");
            }
        //2.校验预约预约时间段，上午  中午  下午 晚上 1 2 3 4
            if(!checkInterval(appointmentReq.getTemporalInterval())){
                return  ResultUtils.returnFail("预约日期时间段有误");
            }
        //3.手机号码校验
            if(!checkphone(appointmentReq.getPhone())){
                return  ResultUtils.returnFail("预约手机号码有误");
            }
        //4.短信验证码校验
        //因为redi服务没有启动，所以没有对验证码进行校验，
//            if(!checkCode(appointmentReq.getPhone(),appointmentReq.getCode())){
//                return ResultUtils.returnFail("预约手机验证码输入有误");
//            };
        //5.地址长度的校验
            if(!checkAddressLength(appointmentReq.getAdress())){
                return ResultUtils.returnFail("地址输入有误");
            }
        //6.评估信息id的校验
            EvaluateDto evaluateDto =evaluateService.getEById(evaluateId);
            if(evaluateDto==null){
                return ResultUtils.returnFail("评估信息Id有误");
            }

        //7.以上校验都通过后，执行，业务提交
           //因为redi服务没有启动，所以手动创建一个Users对象来测试
           // String token =  request.getHeader("token");
           // Users users=tokenService.getLoginUser(token);
            Users users=new Users();
            users.setId(new Long(4)); //模拟token取对对象


            appointmentReq.setUserId(users.getId());
             String orderNo= null;
        try {
            orderNo = maintainOrderService.submit(appointmentReq,evaluateId,evaluateDto.getModel().getId());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //8.数据返回
        return ResultUtils.returnDataSuccess(orderNo);
    }


        private boolean  checkAppDate(java.util.Date appDate){
            java.util.Date currentDate= DateUtils.getCurrentDate(DateUtils.YYYY_MM_DD);
            //大于等于今天并且4天内
            if(appDate.compareTo(currentDate)>=0&&appDate.compareTo(DateUtils.addDate(currentDate,4))<=0){
                return true;
            }
            return false;
        }

        private boolean checkInterval(Integer time){
            if(time>0&&time<=4){
                return true;
            }
            return false;

        }

       private boolean  checkphone(String phone){
            if(!StringUtils.isBlank(phone)){
                if(phone.length()==11&&phone.startsWith("1")){
                    return true;
                }
            }
            return false;
       }

        private boolean checkCode(String phone,String billcode){
            String key= Constants.Redis.PREFIX_SMS+2+":"+phone;
            String code= (String) redisUtil.get(key);
            if(!StringUtils.isBlank(code)&&code.equals(billcode)){
                return true;
            }
            return false;
        }

       private  boolean checkAddressLength(String address){
            if(!StringUtils.isBlank(address)&&address.length()<100){
                return true;
            }
            return false;
       }
}
